<template>
	<view class="container">
		<view class="topperInfo" :class="{ gq: yxqk == 0, wsx: yxqk == 2 }">
			<view class="baseinfo">
				<view>车牌号：{{ cph }}</view>
				<view>入灌卡口：{{ kakou }}</view>
				<view>企业名称：{{ qymc }}</view>
				<view class="icon"></view>
			</view>
			<view class="codearea">
				<view class="top">
					<view class="topitem" :class="{ gq: yxqk == 0, wsx: yxqk == 2 }">
						<view class="gray">通行日期：</view>
						<view class="date">{{ txrq | rqfilter}}</view>
					</view>
					<view class="topitem" v-if="yxqk != 2">
						<!-- yxqk 0失效,1有效,2暂未生效 -->
						<view class="gray">剩余有效时长：</view>
						<view class="sc"><u-count-down :time="time" format="HH:mm:ss" @finish="finishcode()"></u-count-down></view>
					</view>
				</view>
				<view class="code" v-show="!showPopup">
					<uqrcode ref="uQRCode" :text="qrmsg" size="200" margin="10" v-if="yxqk == 1" />
					<uqrcode ref="uQRCode" :text="qrmsg" size="200" margin="10" foregroundColor="#d0605f" v-if="yxqk == 0" />
					<uqrcode ref="uQRCode" :text="qrmsg" size="200"  margin="10" foregroundColor="#333" v-if="yxqk == 2" />
				</view>
			</view>
		</view>

		
		<view class="list">
			<view class="list-item" v-if="isLeaving || canLeave">
				<view class="right act">
					<view class="btn" v-if="isLeaving == '1'" @click="showGuijiPopLk()">行程报备中...</view>
					<view class="btn" v-if="canLeave && isLeaving == '0'" @click="leaveGn()">离灌报备</view>
					<view class="btn btngray" v-if="isLeaving == '2'">已离灌</view>
				</view>
			</view>
			<view class="list-item" v-for="(item, i) in list" :key="i">
				<view class="">{{ item.mddName }}</view>
				<!-- mddStatus空，未开始，1，启程，2，到达 -->
				<view class="flex" v-if="item.mddStatus == 2">
					<view>到达时间: {{ item.arriveTime }}</view>
				</view>
				
				<view v-if="item.mddStatus == 1">
					<view class="flex" v-if="item.time > 0">
						剩余时间：
						<u-count-down :time="item.time" format="HH:mm:ss" :autoStart="item.mddStatus == 1" :ref="item.mddId" @finish="finish(i)"></u-count-down>
					</view>
					<view class="flex" v-else>
						前往目的地超时
					</view>
				</view>
				<view v-if="item.mddStatus == 0">
					<view class="flex">
						 {{i ? '未启程' : '等待放行'}}
					</view>
				</view>
				
				
				
				<view class="guijiPopup">
					<u-popup :show="showPopup" mode="center" @close="closeCommonPopup()" @cancel="closeCommonPopup()"
						@open="openCommonPopup()" :closeOnClickOverlay="true">
						<view class="popInfo" v-if="popupInfo">
							<map :latitude="popupInfo.lat" :scale="10" ref="map" :longitude="popupInfo.lng" :markers="popupInfo.covers" width="720rpx" height="680rpx">
							</map>
							<view class="info" v-if="!popupInfo.leaving">
								<view class="len"><view class="key">距离目的地:</view> <view class="value">{{popupInfo.distance}}</view></view>
								<view class="len"><view class="key">剩余时间:</view> <view class="value">
									<u-count-down :time="popupInfo.leftTime" format="HH:mm:ss" :autoStart="true" @finish="finish(i)"></u-count-down>
								</view></view>
							</view>
							<view class="info" v-else>
								<view class="len"><view class="key">返程报备中……</view>
								<view class="valuesmall">待卡口工作人员扫码确定。惠运码状态若未及时更新，请手动下拉刷新</view></view>
							</view>
						</view>
					</u-popup>
				</view>


				<view class="right">
					<!-- 此版本暂时不显示行程报备 -->
					<!-- <view class="btn" @click="xcbb(item, i)" v-if="!item.mddStatus && yxqk == 1">行程报备</view> -->
					<view class="btn" v-if="item.mddStatus == 1" @click="showGuijiPop(item)">行程报备中...</view>
					<view class="btn" v-if="item.canStart" @click="startRun(item)">点击启程</view>
					<view class="btn btngray" v-if="item.mddStatus == 2">已到达</view>
				</view>
			</view>
		</view>
	</view>
</template>
<!-- https://ext.dcloud.net.cn/plugin?id=1287  二维码插件
				https://www.uviewui.com/components/countDown.html 倒计时插件
				-->
<script>
import getLocation from '@/utils/getLocation.js';
import { mapState, mapMutations } from 'vuex';
import mathUtil from '@/utils/mathUtil.js'
import sceneMixins from '@/utils/sceneMixins.js';
export default {
	mixins: [getLocation, sceneMixins],
	// 过期，未开始，进行中，距离24点的时长
	data() {
		return {
			openId: '',
			qrmsg: '',
			cph: '',
			kakou: '',
			qymc: '',
			txrq: '',
			yxqk: 2, //0失效,1有效,2暂未生效
			time: 0,
			// time：目的地的倒计时是截止时间和当前时间的时间差
			list: [],
			showPopup: false,
			popupInfo: '',
			canLeave: 0, // 1可以 0 不可以
			isLeaving: 0 // 1是的 2已离开
		};
	},
	options: { styleIsolation: 'shared' },
	computed: {
		...mapState(['lnglat', 'globalConfig'])
	},
	onLoad(options) {
		var vm = this;
		vm.bbid = options.id;
        // vm.uploadByListen = wx.canIUse('startLocationUpdateBackground');
        vm.uploadByListen = wx.canIUse('startLocationUpdate');
        // vm.uploadByListenBackground = wx.canIUse('startLocationUpdateBackground');
		if (options.title) {
			uni.setNavigationBarTitle({
				title: options.title
			});
		}
		// this.checkXc();
	},
    mounted: function () {
      var vm = this;
      uni.showLoading();
      vm.waitVariable('bbid').then(() => {
          vm.loadHymInfo();
      })  
    },
	filters: {
		rqfilter: function (v) {
			return v.slice(5)
		}
	},
	methods: {
		...mapMutations(['setPosition']),
		loadHymInfo() {
			var vm = this;
			vm.getAndLoad('获取惠运码详情', '/mobile/ymt/huoyun/mddsb/getQRInfo.jsp?bbid=' + vm.bbid, function(res) {
				uni.hideLoading();
				var data = res.data;
				vm.qrmsg = data.qrmsg;
				vm.cph = data.cph;
				vm.kakou = data.kakou;
				vm.qymc = data.qymc;
				vm.txrq = data.txrq;
				vm.yxqk = data.yxqk;
				vm.isLeaving = data.isLeaving;
				
				// debugger
				// vm.yxqk = 1;
				// vm.time = 0;
				// return;

				uni.stopPullDownRefresh()
				// 如果有效 显示剩余有效时长
				if (Number(vm.yxqk) == 1) {
					// 有效
					// vm.time = new Date(vm.txrq.replace(/-/g, '/') + ' 23:59:59').getTime() - new Date().getTime() + 3600 * 8 * 1000;
					// 现在根据 gqsj计算
					vm.time = new Date(data.gqsj.replace(/-/g, '/')).getTime() - new Date().getTime();
				}
				
				data.mddArray.forEach(obj => {
					if (obj.mddStatus == '启程' || obj.mddStatus == '1') {
						obj.time = new Date(obj.startTime.replace(/-/g, '/')).getTime() + Number(obj.mddLimit) * 60 * 60 * 1000 - new Date().getTime();
					} else if (obj.mddStatus == '空' || obj.mddStatus == '') {
						obj.time = Number(obj.mddLimit) * 60 * 60 * 1000;
					}
				});
				
				var canStartMddIndex = data.mddArray.findIndex((n, index) => {
						return !n.mddStatus;
				});
				if (canStartMddIndex > 0) {
					 var lastMdd = data.mddArray[canStartMddIndex - 1];
					 if (lastMdd.mddStatus == '2') {
						 data.mddArray[canStartMddIndex].canStart = true;
					 }
				}
				
				vm.list = data.mddArray;
				
				if (data.yxqk == '1') {
					var activeMdd = data.mddArray.find(n => {
						return n.mddStatus == '1';
					});
					// debugger
					// 找到启程的目的地
					if (activeMdd) {
						// 开始上报经纬度
						vm.activeMdd = activeMdd;
						vm.startLogPosition();
					} else {
						vm.canLeave = vm.checkCanLeave();
						if (vm.canLeave && vm.isLeaving) {
							vm.startLogPosition();
						} else {
							// 等待卡口放行
							global.reloadInfoTimeout = setTimeout(() => {
								vm.loadHymInfo();
							}, 60000);	
						}
					}
				}
				
			});
		},
		checkCanLeave: function () {
			var vm = this;
			if (vm.yxqk == '1') {
				return vm.list.every(n => n.mddStatus == '2');
			} else {
				return 0;
			}
		},
		
		checkXc() {
			this.list.map(obj => {
				if (obj.status == 2) {
					this.startLogPosition(obj);
				}
			});
		},
		finishcode() {
			console.log('码过期，');
			this.yxqk = 0;
		},
		finish(i) {
			this.$set(this.list[i], 'cs', true);
			console.log('结束' + i);
		},
		xcbb(item, i) {
			this.$refs[item.mddId][0].start();
			this.startLogPosition(item);
		},
		startLogPosition: function() {
			var vm = this;
            clearTimeout(global.reloadInfoTimeout);
            vm.stopReportGuiji().then(() => {
                uni.setKeepScreenOn({
                	keepScreenOn: true
                });
                vm.doWxLogin().then(res => {
                	vm.openId = res.openId;
                    if (vm.uploadByListen) {
                        vm.listenUserLocation(vm.logPosition2, false)
                    } else {
                        vm.logPosition();
                        global.hymGjsbInterval = setInterval(() => {
                        	vm.logPosition();
                        }, 15000);
                    }
                });
            })
		},
        stopReportGuiji: function () {
            uni.setKeepScreenOn({keepScreenOn: false});
            clearInterval(global.hymGjsbInterval);
            return this.stopListenUserLocation();
        },
		showGuijiPop: function (item) {
			var vm = this;
			if (this.lnglat) {
				var distance = mathUtil.getDistance(vm.lnglat[1], vm.lnglat[0], item.mddLat, item.mddLng);
				if (distance > 1000) {
					distance = (distance / 1000).toFixed(1) + 'km'
				} else {
					distance = (distance / 1).toFixed(0) + 'm';
				}
				
				var leftTime = vm.getLeftTime();
				this.popupInfo = {
					lng: this.lnglat[0],
					lat: this.lnglat[1],
					distance,
					leftTime,
					leaving: false,
					covers: [
						{
							id: 100,
							latitude: this.lnglat[1],
							longitude: this.lnglat[0],
							width: 30, height: 30,
							iconPath: '/static/imgs/zhuanyundian.png',
						}, {
							id: 200,
							latitude: item.mddLat,
							longitude: item.mddLng,
							width: 30, height: 30,
							iconPath: '/static/imgs/chubeidian.png',
						}
					]
				}
				this.openCommonPopup();
			}
		},
		showGuijiPopLk: function () {
			var vm = this;
			if (this.lnglat) {
				this.popupInfo = {
					lng: this.lnglat[0],
					lat: this.lnglat[1],
					distance: 0,
					leftTime: 0,
					leaving: true,
					covers: [
						{
							id: 100,
							latitude: this.lnglat[1],
							longitude: this.lnglat[0],
							width: 30, height: 30,
							iconPath: '/static/imgs/zhuanyundian.png',
						}
					]
				}
				this.openCommonPopup();
			}
		},
		getLeftTime: function () {
			var item = this.activeMdd;
			var time = new Date((item.startTime + ' 00:00:00').slice(0, 19).replace(/-/g, '/')).getTime() + Number(item.mddLimit) * 60 * 60 * 1000 - new Date().getTime();
			return time;
		},
		logPosition() {
			var vm = this;
			vm.getUserLocation().then(res => {
				vm.setPosition(res);
				var activeMdd = vm.activeMdd;
				
				if (vm.popupInfo) {
					var leftTime = 0;
					var distance = 0;
					if (vm.activeMdd) {
						var item = vm.activeMdd;
						var distance = mathUtil.getDistance(vm.lnglat[1], vm.lnglat[0], item.mddLat, item.mddLng);
						if (distance > 1000) {
							distance = (distance / 1000).toFixed(1) + 'km'
						} else {
							distance = (distance / 1).toFixed(0) + 'm';
						}
						leftTime = vm.getLeftTime();
					}
					vm.popupInfo.leftTime = leftTime;
					vm.popupInfo.distance = distance;
					vm.popupInfo.leaving = vm.isLeaving;
					vm.popupInfo.covers = [
						{
							id: 100,
							latitude: vm.lnglat[1],
							longitude: vm.lnglat[0],
							width: 30, height: 30,
							iconPath: '/static/imgs/zhuanyundian.png',
						}
					];
					if (vm.activeMdd) {
						vm.popupInfo.covers.push({
							id: 200,
							latitude: item.mddLat,
							longitude: item.mddLng,
							width: 30, height: 30,
							iconPath: '/static/imgs/chubeidian.png',
						})	
					}
				}
				// debugger
				vm.getAndLoad('上报点位', `/mobile/api/uploadLoc.jsp?` + 
					vm.$Util.stringify({
						wxid: vm.openId,
						userId: '',
						applyId: vm.bbid, 
						destId: activeMdd ? activeMdd.mddId : '',
						lng: res.longitude,
						lat: res.latitude,
					}), function(res2) {
						if (activeMdd) {
							var distance = mathUtil.getDistance(res.latitude, res.longitude, activeMdd.mddLat, activeMdd.mddLng);
							if (distance <= vm.globalConfig.arriveDistance) {
							// if (distance <= 300000) {
								vm.arriveMdd();
							}
						}
				});
			});
		},
        logPosition2(res) {
        	var vm = this;

            vm.setPosition(res);
            var activeMdd = vm.activeMdd;
            
            if (vm.popupInfo) {
            	var leftTime = 0;
            	var distance = 0;
            	if (vm.activeMdd) {
            		var item = vm.activeMdd;
            		var distance = mathUtil.getDistance(vm.lnglat[1], vm.lnglat[0], item.mddLat, item.mddLng);
            		if (distance > 1000) {
            			distance = (distance / 1000).toFixed(1) + 'km'
            		} else {
            			distance = (distance / 1).toFixed(0) + 'm';
            		}
            		leftTime = vm.getLeftTime();
            	}
            	vm.popupInfo.leftTime = leftTime;
            	vm.popupInfo.distance = distance;
				vm.popupInfo.leaving = vm.isLeaving;
            	vm.popupInfo.covers = [
            		{
            			id: 100,
            			latitude: vm.lnglat[1],
            			longitude: vm.lnglat[0],
            			width: 30, height: 30,
            			iconPath: '/static/imgs/zhuanyundian.png',
            		}
            	];
            	if (vm.activeMdd) {
            		vm.popupInfo.covers.push({
            			id: 200,
            			latitude: item.mddLat,
            			longitude: item.mddLng,
            			width: 30, height: 30,
            			iconPath: '/static/imgs/chubeidian.png',
            		})	
            	}
            }
            var time = new Date().getTime();
            // uni.$u.toast('得到轨迹数据');
            // 如果移动距离超过30米 或者 超过10秒未上报，则上报
			
            if (!global.lastLocationReportTime ||
                (time - global.lastLocationReportTime > 10000) ||
                mathUtil.getDistance(vm.lnglat[1], vm.lnglat[0], res.latitude, res.longitude) > 30
            ) {
                vm.getAndLoad('上报点位', `/mobile/api/uploadLoc.jsp?` +
                    vm.$Util.stringify({
                        wxid: vm.openId,
                        userId: '',
                        applyId: vm.bbid, 
                        destId: activeMdd ? activeMdd.mddId : '',
                        lng: res.longitude,
                        lat: res.latitude,
                    }), function(res2) {
                        global.lastLocationReportTime = time;
						if (activeMdd) {
							var distance = mathUtil.getDistance(res.latitude, res.longitude, activeMdd.mddLat, activeMdd.mddLng);
							if (distance <= vm.globalConfig.arriveDistance) {
							// if (distance <= 300000) {
							    vm.arriveMdd();
							}
						}
                });
            }
        },
		startRun: function (item) {
			var vm = this;
			vm.stopReportGuiji();
			vm.getAndLoad('启程', '/mobile/ymt/huoyun/mddsb/qicheng.jsp?mddId=' + item.mddId, function (res) {
				if (res.success) {
					uni.$u.toast('启动成功，开始上报您的轨迹');
					vm.loadHymInfo();
				} else {
					uni.$u.toast(res.msg);
				}
			})
		},
		leaveGn: function () {
			var vm = this;
			vm.getAndLoad('离灌报备', `/mobile/ymt/huoyun/leave/leave.jsp?openId=${vm.openId}&bbid=${vm.bbid}`, function (res) {
				if (res.success) {
					uni.$u.toast('已报备，开始上报您的轨迹');
					vm.loadHymInfo();
				} else {
					uni.$u.toast(res.msg);
				}
			})
		},
		closeCommonPopup: function() {
			this.showPopup = false;
		},
		openCommonPopup: function() {
			var vm = this;
			this.showPopup = true;
		},
		arriveMdd: function () {
			var vm = this;
			vm.stopReportGuiji();
			vm.getAndLoad('目的地到达', '/mobile/ymt/huoyun/mddsb/daoda.jsp?mddId=' + vm.activeMdd.mddId, function (res) {
				if (res.success) {
					uni.$u.toast('目的地已到达');
					vm.loadHymInfo();
				} else {
					uni.$u.toast(res.msg);
				}
			})
		}
	},
	onPullDownRefresh: function () {
		this.stopReportGuiji();
		uni.showLoading();
		this.loadHymInfo();
	},
	destroyed() {
        clearTimeout(global.reloadInfoTimeout)
        this.stopReportGuiji();
	}
};
</script>

<style lang="scss" scoped>
.tip {
	color: red;
}
.flex {
	display: flex;
}
.list {
	margin-top: 20rpx;
	.list-item {
		padding: 30rpx 20rpx;
		font-size: 30rpx;
		position: relative;
		background-color: #fff;
		line-height: 50rpx;
		.right {
			position: absolute;
			right: 20rpx;
			bottom: 20rpx;
			&.act {
				position: relative;
				padding: 0 0 20rpx 0;
				right: 0;
			}
		}
		&:not(:last-child) {
			border-bottom: 1px solid #ccc;
		}
	}
}
.btn {
	color: #fff;
	font-size: 28rpx;
	padding: 8rpx 20rpx;
	border-radius: 5rpx;
	margin-top: 10rpx;
	background-color: #2f9ef6;
	display: inline-block;
	float: right;
	line-height: 34rpx;
	&.btngray {
		background-color: #969696;
	}
}
.baseinfo {
	// background-color: #26a37e;
	font-size: 28rpx;
	padding: 40rpx 30rpx;
	position: relative;
	color: #fff;
	line-height: 42rpx;
	.icon {
		width: 127rpx;
		height: 120rpx;
		background: url('/static/imgs/yx.png') no-repeat center;
		background-size: 100% 100%;
		position: absolute;
		right: 30rpx;
		top: 40rpx;
	}
}
.sc {
	margin-top: 10rpx;
}
/deep/.sc .u-count-down__text {
	font-weight: bold;
	font-size: 50rpx;
}
.topperInfo {
	background-color: #26a37e;
}
.gray {
	color: #fff;
	font-size: 26rpx;
}
.codearea {
	padding: 50rpx 100rpx;
	// background-color: #fff;
	.top {
		display: flex;
		color: #333;
		justify-content: space-around;
		.topitem {
			// flex: 1;
			
			.date {
				font-weight: bold;
				font-size: 56rpx;
				color: #fff;
				height: 80rpx;
				line-height: 80rpx;
			}

			.sc {
				font-weight: bold;
				font-size: 44rpx;
				margin: 0;
				/deep/ .u-count-down__text {
					color: #fff;
					font-size: 56rpx;
					height: 80rpx;
					line-height: 80rpx;
				}
			}
		}
	}
}
.gq {
	background-color: #d0605f; 
	.baseinfo {
		.icon {
			background: url('/static/imgs/sx.png') no-repeat center;
			background-size: 100% 100%;
		}
	}
}
.wsx {
	background-color: #777;
	.baseinfo {
		.icon {
			background: url('/static/imgs/wsx.png') no-repeat center;
			background-size: 100% 100%;
		}
	}
}
// .wsx .date {
// 	color: #606266 !important;
// }
// .gq .date {
// 	color: #d0605f !important;
// }
.code {
	width: 200px;
	margin: 20rpx auto;
}

.guijiPopup {
	/deep/ .u-popup__content {
		width: 720rpx;
		height: 770rpx;
		.popInfo {
			map {
				width: 100%;
				height: 680rpx;
			}
			.info {
				display: flex;
				justify-content: space-around;
				height: 90rpx;
				align-items: center;
				font-size: 30rpx;
				line-height: 40rpx;
				.len {
					display: flex;
					align-items: center;
					flex-direction: column;
					/deep/ .u-count-down__text {
						font-size: 30rpx;
						margin-left: 10rpx;
					}
					.valuesmall {
						font-size: 22rpx;
						line-height: 24rpx;
						color: #8a8a8a;
					}
				}
			}
		}
	}
}
</style>
